package com.chaoli.reggie_diy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chaoli.reggie_diy.common.BaseContext;
import com.chaoli.reggie_diy.common.R;
import com.chaoli.reggie_diy.domain.ShoppingCart;
import com.chaoli.reggie_diy.mapper.ShoppingCartMapper;
import com.chaoli.reggie_diy.service.ShoppingCartService;
import org.springframework.stereotype.Service;

import java.security.acl.LastOwnerException;

@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {
    /**
     * 减少购物车中的菜品或者套餐数量
     *
     * @param shoppingCart
     * @return
     */
    @Override
    public R<ShoppingCart> jianshao(ShoppingCart shoppingCart) {
        LambdaQueryWrapper<ShoppingCart> shoppingCartQueryWrapper = new LambdaQueryWrapper<>();
        Long dishId = shoppingCart.getDishId();
        Long setmealId = shoppingCart.getSetmealId();

        if (dishId != null) {
            shoppingCartQueryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
            ShoppingCart shoppingCart1 = this.getOne(shoppingCartQueryWrapper);
            shoppingCart1.setNumber(shoppingCart1.getNumber() - 1);
            Integer latestNumber = shoppingCart1.getNumber();
            if (latestNumber > 0) {
                this.updateById(shoppingCart1);
            } else if (latestNumber == 0) {
                this.removeById(shoppingCart1.getId());
            } else if (latestNumber < 0) {
                return R.error("操作异常!!!");
            }
            return R.success(shoppingCart1);
        }

        if (setmealId != null) {
            shoppingCartQueryWrapper.eq(ShoppingCart::getSetmealId, setmealId);
            ShoppingCart shoppingCart2 = this.getOne(shoppingCartQueryWrapper);
            shoppingCart2.setNumber(shoppingCart2.getNumber() - 1);
            Integer latestNumber = shoppingCart2.getNumber();
            if (latestNumber > 0) {
                this.updateById(shoppingCart2);
            } else if (latestNumber == 0) {
                this.removeById(shoppingCart2.getId());
            } else if (latestNumber < 0) {
                return R.error("操作异常");
            }
            return R.success(shoppingCart2);
        }
        return R.error("操作异常!!!");
    }
}
